package me.android.library.utils.android;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import mylab.utils.common.IoUtil;

@SuppressLint("StaticFieldLeak")
@Slf4j
@UtilityClass
public class ResourcesUtil {
    // 资源类型常量
    public final String TYPE_DRAWABLE = "drawable";
    public final String TYPE_STRING = "string";
    public final String TYPE_LAYOUT = "layout";
    public final String TYPE_COLOR = "color";
    public final String TYPE_DIMEN = "dimen";
    public final String TYPE_ID = "id";

    // 资源 ID 缓存（避免重复反射调用）
    private final Map<String, Integer> RESOURCE_CACHE = Maps.newHashMap();

    public Uri res2Uri(int resId) {
        String pgName = ContextUtil.getAppContext().getPackageName();
        return Uri.parse("android.resource://" + pgName + "/" + resId);
    }


    /**
     * 将资源文件复制到应用私有目录（优化版）
     *
     * @param context  上下文
     * @param resId    资源ID
     * @param fileName 目标文件名
     * @return true 表示成功，false 表示失败
     */
    public boolean copyResourceToPrivateFile(Context context, int resId, String fileName) {
        if (context == null) return false;

        int mode = Context.MODE_PRIVATE;
        try (InputStream in = context.getResources().openRawResource(resId);
             FileOutputStream out = context.openFileOutput(fileName, mode)) {

            byte[] buffer = new byte[4096]; // 增大缓冲区提高性能
            int bytesRead;

            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            return true; // 复制成功
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从原始资源读取字符串
     */
    public String raw2String(int resid) {
        byte[] data = raw2Bytes(resid);
        return new String(data, StandardCharsets.UTF_8);
    }

    /**
     * 从原始资源读取字节流
     */
    public byte[] raw2Bytes(int resid) {
        try (InputStream stream = ContextUtil.getResources().openRawResource(resid)) {
            return IoUtil.readBytes(stream);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 若是字符串资源，则取其资源值，否则返回原始值
     */
    public String getStringOrFromRes(String rawString) {
        if (!Strings.isNullOrEmpty(rawString) && rawString.startsWith("@string/")) {
            int resId = getResourceId(rawString);
            return resId <= 0 ? rawString : ContextUtil.getAppContext().getString(resId);
        } else {
            return rawString;
        }
    }

    /**
     * 根据资源名称获取资源 ID（兼容 Android 14+）
     *
     * @param resourceName 资源名称（格式："type/name" 或 "package:type/name"）
     * @return 资源 ID，找不到时返回 0
     */
    @SuppressLint("DiscouragedApi")
    public int getResourceId(String resourceName) {

        // 检查缓存
        String cacheKey = resourceName;
        if (RESOURCE_CACHE.containsKey(cacheKey)) {
            return Objects.requireNonNull(RESOURCE_CACHE.get(cacheKey));
        }

        Context context = ContextUtil.getAppContext();

        try {
            // 移除可能的 @ 前缀
            if (resourceName.startsWith("@")) {
                resourceName = resourceName.substring(1);
            }

            String packageName = context.getPackageName();
            String type = null;
            String name = null;

            // 解析资源名称
            if (resourceName.contains(":")) {
                // 格式：package:type/name
                String[] packageParts = resourceName.split(":", 2);
                packageName = packageParts[0];
                resourceName = packageParts[1];
            }

            if (resourceName.contains("/")) {
                // 格式：type/name
                String[] typeParts = resourceName.split("/", 2);
                type = typeParts[0];
                name = typeParts[1];
            } else {
                // 默认使用 drawable 类型
                type = TYPE_DRAWABLE;
                name = resourceName;
            }

            // 获取资源 ID
            int resId;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                // Android 14+ 使用 PackageManager
                PackageManager pm = context.getPackageManager();
                resId = pm.getResourcesForApplication(packageName).getIdentifier(name, type, packageName);
            } else {
                // 旧版本使用 Resources
                Resources resources = context.getResources();
                resId = resources.getIdentifier(name, type, packageName);
            }

            // 缓存结果
            RESOURCE_CACHE.put(cacheKey, resId);
            return resId;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 清除资源缓存
     */
    public void clearResourceCache() {
        RESOURCE_CACHE.clear();
    }

}
